package com.beijiteshop.libcommon.login

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import java.lang.NullPointerException

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/12 20:53
 * @Description
 */
class UserInfoUtil private constructor(){

    companion object{
        private const val SP_NAME = "userinfo"
        private const val SP_LOGIN_INFO = "sp_login_info"
        private const val SP_USER_INFO = "sp_user_info"

        private lateinit var mContext: Context
        private lateinit var mSP: SharedPreferences
        private lateinit var mSpEditor: SharedPreferences.Editor

        private var singleton: UserInfoUtil? = null
        get() {
            if (field == null){
                singleton = UserInfoUtil()
            }
            return field
        }

        @Synchronized
        fun init(context: Context){
            mContext = context
            initSP(context)
        }

        private fun initSP(context: Context){
            mSP = context.getSharedPreferences(SP_NAME,
                Context.MODE_PRIVATE)
            mSpEditor = mSP.edit()
        }

        @Synchronized
        fun getInstance(): UserInfoUtil{
            if (mContext == null){
                throw NullPointerException("please init UserInfoUtil in your Application")
            }
            return singleton!!
        }
    }

    /**
     * 更新登录信息
     */
    fun updateLoginInfo(loginInfo: LoginInfo){
        val info = Gson().toJson(loginInfo)
        mSpEditor.putString(SP_LOGIN_INFO,info)
        mSpEditor.apply()
    }

    fun getLoginInfo(): LoginInfo?{
        val info = mSP.getString(SP_LOGIN_INFO,null)
        if (!info.isNullOrEmpty()){
            return Gson().fromJson(info,LoginInfo::class.java)
        }
        return null
    }

    fun isLogin(): Boolean{
        return getLoginInfo() != null
    }

    fun clear(){
        mSpEditor.clear().commit()
    }

    /**
     * 更新用户信息
     */
    fun updateUserInfo(userInfo: UserInfo){
        val info = Gson().toJson(userInfo)
        mSpEditor.putString(SP_USER_INFO,info)
        mSpEditor.apply()
    }

    fun getUserInfo(): UserInfo?{
        val info = mSP.getString(SP_USER_INFO,null)
        if (!info.isNullOrEmpty()){
            return Gson().fromJson(info,UserInfo::class.java)
        }
        return null
    }

}